from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin

from web import models
from django.conf import settings


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户已经登录，则request中赋值"""

        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.user_obj = user_obj
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        if not user_obj:
            return redirect('/web/login/')
